/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
limitations under the License.*/

package zuo.biao.library.manager;

import com.alibaba.fastjson.JSON;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import zuo.biao.library.util.Log;
import zuo.biao.library.util.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**磁盘缓存类
 * @author Lemon
 * @param <T> 缓存的数据类
 * @use new Cache<T>(context, clazz, path).xxxMethod(...);具体参考.CacheManager
 */
public class Cache<T> {
    private static final String TAG = "Cache";

    private Class<T> clazz;
    private Preferences sp;

    public Cache(Class<T> clazz, Context context, String name) {
        DatabaseHelper databaseHelper = new DatabaseHelper(context); // context 入参类型为 ohos.app.Context
        Preferences preferences = databaseHelper.getPreferences(name);
        this.clazz = clazz;
        this.sp = preferences;
    }

    /**获取列表大小
     * @return int
     */
    public int getSize() {
        Map<String, ?> map = sp.getAll();
        return map == null ? 0 : map.size();
    }

    /**保存
     * @param map m
     */
    public void saveList(Map<String, T> map) {
        if (map == null) {
            Log.error(TAG, "saveList  map == null >> return;");
            return;
        }
        Set<String> keySet = map.keySet();
        if (keySet != null) {
            for (String id : keySet) {
                save(id, map.get(id));
            }
        }
    }

    /**保存
     * @param key k
     * @param value v
     */
    public void save(String key, T value) {
        if (StringUtil.isNotEmpty(key, true) == false || value == null) {
            Log.error(TAG, "save StringUtil.isNotEmpty(key, true) == false || value == null >> return;");
            return;
        }
        key = StringUtil.getTrimedString(key);

        sp.delete(key).putString(key, JSON.toJSONString(value));
        sp.flushSync();
    }

    /**判断是否已存
     * @param key key
     * @return boolean
     */
    public boolean isContain(String key) {
        if (StringUtil.isNotEmpty(key, true) == false) {
            Log.error(TAG, "isContain StringUtil.isNotEmpty(key, true) == false >> return false;");
            return false;
        }

        return sp.hasKey(StringUtil.getTrimedString(key));
    }

    /**
     * 获取
     * @param key key
     * @return T
     */
    public T get(String key) {
        if (StringUtil.isNotEmpty(key, true) == false) {
            Log.error(TAG, "get (sp == null" + " || StringUtil.isNotEmpty(key, true) == false >> return null; ");
            return null;
        }

        return JSON.parseObject(sp.getString(StringUtil.getTrimedString(key), null), clazz);
    }

    /**ROOT
     * 获取列表
     * @return Map
     */
    public Map<String, String> getMap() {
        try {
            return (Map<String, String>) sp.getAll();
        } catch (Exception e) {
            Log.error(
                    TAG,
                    "getMap try { return (Map<String, String>) sp.getAll();"
                            + "}catch(Exception e) {\n "
                            + e.getMessage());
        }
        return null;
    }

    /**ROOT
     * 获取列表
     * @return Set
     */
    public Set<String> getKeySet() {
        Map<String, String> map = getMap();
        return map == null ? null : map.keySet();
    }

    /**ROOT
     * 获取列表
     * @param start < 0 ? all : [start, end]
     * @param end end
     * @return List
     */
    public List<T> getValueList(int start, int end) {
        List<T> list = getAllValueList();
        return start < 0 || start > end || list == null || end >= list.size() ? list : list.subList(start, end);
    }
    /**ROOT
     * 获取列表,顺序由keyList指定
     * @param keyList keyList
     * @return List
     */
    public List<T> getValueList(List<String> keyList) {
        if (keyList != null) {
            List<T> list = new ArrayList<T>();
            T data;
            for (String key : keyList) {
                data = get(key);
                if (data != null) {
                    list.add(data);
                }
            }
            return list;
        }
        return null;
    }
    /**ROOT
     * 获取列表
     * @return List
     */
    public List<T> getAllValueList() {
        Map<String, String> map = getMap();
        if (map != null) {
            List<T> list = new ArrayList<T>();
            T data;
            for (String value : map.values()) {
                data = JSON.parseObject(value, clazz);
                if (data != null) {
                    list.add(data);
                }
            }
            return list;
        }
        return null;
    }

    /**删除
     * @param key key
     */
    public void remove(String key) {
        if (StringUtil.isNotEmpty(key, true) == false) {
            Log.error(
                    TAG,
                    "deleteGroup  context == null " + " || StringUtil.isNotEmpty(groupName, true) == fal >> return;");
            return;
        }

        sp.delete(StringUtil.getTrimedString(key));
        sp.flushSync();
    }
}
